﻿using System;
using System.Web.Hosting;
using System.Web.Services;
using System.Xml;
using Microsoft.SharePoint;

namespace SP14.WebServices
{
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1), WebService(Namespace="http://schemas.microsoft.com/sharepoint/soap/")]
    public class ExternalList : WebService
    {
        [WebMethod]
        public XmlNode GetListAndView(string listName, string viewName)
        {
            XmlNode lv = null;
            using (HostingEnvironment.Impersonate())
            {
                SP14.ExternalList.ListWebSvc.Lists client = new SP14.ExternalList.ListWebSvc.Lists();
                client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                client.Url = string.Format("{0}/_vti_bin/lists.asmx", SPContext.Current.Web.Url.Replace("https://", "http://"));
                lv = client.GetListAndView(listName, viewName); 
            }
            if (lv != null)
            {
                lv.FirstChild.Attributes["HasExternalDataSource"].Value = "False";
            }
            return lv;
        }

        [WebMethod]
        public XmlNode GetListItems(string listName, string viewName, XmlNode query, XmlNode viewFields, string rowLimit, XmlNode queryOptions, string webID)
        {
            var list = SPContext.Current.Web.Lists[new Guid(listName)];
            var view = list.Views[new Guid(viewName)];
            var rs = list.GetItems(view);
            string xml = rs.Xml;
            var doc = new XmlDocument();
            doc.LoadXml(xml);
            return doc;
        }
    }
}
